package com.ytjj.common.utils;

import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 每日自增变量值
 */
@Component
public class EveryDayIncrementVarUtil {
    @Autowired
    private RedisService redisService;
    /**
     * 获取每天的递增值
     * @return
     */
    public String increByEveryDay() {
        String orderNoNum = redisService.get(RedisConstants.ORDER_NO_KEY);
        if (StringUtils.isEmpty(orderNoNum)) {
            orderNoNum = "0000000001";
            redisService.set(RedisConstants.ORDER_NO_KEY, orderNoNum);
        }else {
            AtomicLong orderNo_l = new AtomicLong(Long.parseLong(orderNoNum));
            String incResult = String.valueOf(orderNo_l.addAndGet(1));

            StringBuilder result = new StringBuilder("");
            switch (incResult.length()) {
                case 1 :
                    result.append("000000000").append(incResult);
                    break;
                case 2 :
                    result.append("00000000").append(incResult);
                    break;
                case 3 :
                    result.append("0000000").append(incResult);
                    break;
                case 4 :
                    result.append("000000").append(incResult);
                    break;
                case 5 :
                    result.append("00000").append(incResult);
                    break;
                case 6 :
                    result.append("0000").append(incResult);
                    break;
                case 7 :
                    result.append("000").append(incResult);
                    break;
                case 8 :
                    result.append("00").append(incResult);
                    break;
                case 9 :
                    result.append("00").append(incResult);
                    break;
                default :
                    result.append(incResult);
                    break;
            }
            redisService.set(RedisConstants.ORDER_NO_KEY, result.toString());
            orderNoNum = result.toString();
        }
        redisService.expire(RedisConstants.ORDER_NO_KEY, getCurTimeDiff());
        return  orderNoNum;
    }

    /**
     * 获取当前时间到第二天凌晨的秒数
     *
     * @return
     */
    public Long getCurTimeDiff() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }
}
